import React, { useEffect } from 'react';
import {
  Form,
  TextField,
} from 'choerodon-ui/pro';
import { useLocation } from 'react-router';

import { CustomSelect } from '@choerodon/components';
import { observer } from 'mobx-react-lite';
import { useTemplateSaveStore } from './stores';
import { templateDataSet } from './stores/templateSaveDataSet';

import './index.less';

const Index = observer(() => {
  const {
    TemplateSaveDs,
    prefix,
    handleSubmit,
    modal,
  } = useTemplateSaveStore();

  const { search } = useLocation();

  useEffect(() => {
    handleGetDataSet();
  }, []);

  const handleGetDataSet = async () => {
    const res = await templateDataSet.query();
    TemplateSaveDs?.current?.set('ciTemplateCategoryId', res?.[0]?.id);
  };

  // eslint-disable-next-line consistent-return
  modal.handleOk(async () => {
    const flag = await TemplateSaveDs?.validate();
    if (flag) {
      const res = await handleSubmit({
        extraData: TemplateSaveDs?.current?.toData(),
        isSaveTemplate: true,
      });
      if (res !== false) {
        window.open(`${window.location.origin}/#/baseBusiness/project-pipeline-template/edit/edit/${res?.id}${search}`);
      }
    } else {
      return false;
    }
  });

  return (
    <>
      <Form dataSet={TemplateSaveDs}>
        <TextField name="name" />
      </Form>
      <p className={`${prefix}-category`}>
        流水线分类
      </p>
      <div className={`${prefix}-container`}>
        <CustomSelect
          onClickCallback={
            (value) => {
              TemplateSaveDs?.current?.set('ciTemplateCategoryId', value?.id);
            }
          }
          data={TemplateSaveDs?.current?.getField('ciTemplateCategoryId')?.options?.toData() || []}
          selectedKeys={TemplateSaveDs?.current?.get('ciTemplateCategoryId') ? TemplateSaveDs?.current?.get('ciTemplateCategoryId') : ''}
          identity="id"
          mode="single"
          customChildren={(item: any) => (
            <div className={`${prefix}-container-item`}>
              <img style={{ width: 56, height: 56 }} src={item.image} alt="" />
              <p>{item.category}</p>
            </div>
          )}
        />
      </div>
    </>
  );
});

export default Index;
